package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     *  导出Excel报表接口
     */
    @Override
    /**导出近30天的运营数据报表
     * @param response
     **/
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30); // 查询近30天的数据
        LocalDate end = LocalDate.now().minusDays(1);// 前一天23：59：59

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime,endTime);
        InputStream inputStream = this.getClass()
                .getClassLoader()
                .getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }


    /**
     * 用户统计
     * dateList 日期列表 totalUserList 总用户列表 newUserList 新增用户列表
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 1. 生成日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(begin.isBefore(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 2. 用户列表
        Map<String,Object> map = new HashMap<>();
        List<Integer> totalUserList = new ArrayList<>();

        List<Integer> newUserList = new ArrayList<>();
        for(LocalDate date : dateList){
            // 查询当天新增用户
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);// 当天开始时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);// 当天结束时间

            //新增用户数量 select count(id) from user where create_time > ? and create_time < ?
            Integer newUser = getUserCount(beginTime, endTime);

            //总用户数量 select count(id) from user where  create_time < ?
            Integer totalUser = getUserCount(null, endTime);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        String dateli = StringUtils.join(dateList, ",");// 字符串" a,b,c  "

        UserReportVO userReportVO = UserReportVO
                .builder()
                .dateList(dateli)  // 使用 String.join() 将列表转换为逗号分隔的字符串
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join( totalUserList,","))
                .build();
        return userReportVO;

    }

    /**
     * 根据时间区间统计用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end", endTime);
        return userMapper.countUser(map);
    }


    /**
     *  销量排行接口
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO saleTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<String> namelist = new ArrayList<>();//商品名称列表 如：鱼香肉丝,宫保鸡丁,水煮鱼
        List<Integer> numberlist = new ArrayList<>();  //销量列表 如：260,215,200

        // select od.name,sum(od.number) count from order_detail od left join orders o on od.order_id=o.id
        // and o.status=5  and o.create_time > ? and o.create_time < ?
        //group by od.name
        //order by count desc
        //LIMIT 0,10;

        // GoodsSalesDTO； 商品名称，销量
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.saleTop10(beginTime,endTime);

        for(GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList){
            namelist.add(goodsSalesDTO.getName());
            numberlist.add(goodsSalesDTO.getNumber());
        }

        // 封装返回数据
        SalesTop10ReportVO salesTop10ReportVO=SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(namelist,","))// 商品名称列表
                .numberList(StringUtils.join(numberlist,","))// 销量列表
                .build();
        return salesTop10ReportVO;
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 1. 查询每一天的订单数量
        List<LocalDate> dateList = new ArrayList<>();// 存放每一天
        dateList.add(begin);
        while(begin.isBefore(end)){// 判断是否到最后一天
            begin = begin.plusDays(1);// 加一天
            dateList.add(begin);
        }

        // 订单数量 , 有效数量
        List<Integer> orderList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();

        Integer totalCount = 0;
        Integer validCount = 0;
        for (LocalDate date : dateList) {
            Map map = new HashMap<>();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date,LocalTime.MAX));

            // 订单总数量 select count(*) from order where create_time > ？ and create_time < ？
            Integer total = orderMapper.countByMap(map);
            totalCount += total;
            orderList.add(total);

            // 有效数量 select count(*) from order where create_time > ？ and create_time < ？AND status = 5
            map.put("status", Orders.COMPLETED);// 已完成订单
            Integer valid = orderMapper.countByMap(map);
            validCount += valid;
            validOrderList.add(valid);
        }

        Double rate = validCount .doubleValue() / totalCount;// 订单完成率

        OrderReportVO orderReportVO = OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))// 日期列表
                .orderCountList( StringUtils.join(orderList,","))// 订单数量
                .validOrderCountList( StringUtils.join(validOrderList,","))// 订单有效数量
                .totalOrderCount(totalCount)// 订单总数
                .validOrderCount(validCount)// 订单有效总数
                .orderCompletionRate(rate) //   订单完成率
                .build();
        return orderReportVO;
    }

    /**
     * 营业额统计接口
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();// 存放每一天
        dateList.add(begin);
        while(begin.isBefore(end)){// 判断是否到最后一天
            begin = begin.plusDays(1);// 加一天
            dateList.add(begin);
        }
        // 每一天的营业额
        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);// 每天开始时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);// 每天结束时间
            // 查询每天的营业额 select sum(amount) from order where create_time > ？ and create_time < ？AND status = 5
            HashMap<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);// 已完成订单状态码

            Double account=orderMapper.getAmountByMap(map);
            account = account == null ? 0.0 : account;
            turnoverList.add(account);
        });

        String join_dateList = StringUtils.join(dateList, ",");//2025-02-26,2025-02-27
        // String join_dateList2 = StringUtil.join( ",",dateList);//[2025-02-26, 2025-02-27 ]


        String join_turnoverList = StringUtils.join(turnoverList,",");
        TurnoverReportVO turnoverReportVO = TurnoverReportVO
                .builder()
                .dateList(join_dateList)
                .turnoverList(join_turnoverList)
                .build();
        return turnoverReportVO;
    }

}
